package cn.tedu.servlet;

import cn.tedu.mvc.core.Handler;
import cn.tedu.mvc.core.HandlerAdapter;
import cn.tedu.mvc.core.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前端控制器
 */
//@WebServlet("/dis/*")
public class DispatcherServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // /dis/reg
        String requestURI = req.getRequestURI();
        // 如果你的路径是注册 ，那我调用注册的servlet来处理
        Handler handler = HandlerMapping.handlerMappingMap.get(requestURI);

        // 调用适配器处理器处理
        HandlerAdapter handlerAdapter = new HandlerAdapter();
        ModelAndView modelAndView = null;
        try {
            modelAndView = handlerAdapter.handle(req,resp,handler);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 响应对象发送给前端
        resp.getWriter().write(modelAndView.toString());
    }
}
